import { ProcessState, StateType, mimeToExtMap } from '@/config';
import { TaskInfo } from '@/entrypoints/hook/useConcurrentRequest';
import { useDirectoryHandle } from '@/entrypoints/hook/useDirectoryHandle';
import { getProductState, removeAllFilesInDirectory, setProductState } from '@/lib/filesystem';
import { addImageWaterMark, createSpliceImage } from '@/lib/meituxiuxiu';
import { getAllFileHandleByDirectoryHandle, getRandomElement } from '@/lib/utils';
import { useSettingsStore } from '@/store';
import { OperationMessageType } from '@/store/message';
import { toast } from 'sonner';
import { useMessage } from './useDiaoxiaomiMessage';
import { useComfyUI } from './useComfyUI';

const processingProduct: Record<string, boolean> = {};
export function useProcess() {
  const { resetMessage, addMessage, resetAndAddMessage } = useMessage();
  const processSettings = useSettingsStore((state) => state.processSettings);
  const isUseAiProcessScenceAndWhiteImages = useSettingsStore(
    (state) => state.processSettings.isUseAiProcessScenceAndWhiteImages,
  );
  const isFilterProcessScenceAndWhiteImages = useSettingsStore(
    (state) => state.processSettings.isFilterProcessScenceAndWhiteImages,
  );
  const isUseProcessSpliceImage = useSettingsStore(
    (state) => state.processSettings.isUseProcessSpliceImage,
  );
  const isRemoveImageInProcess = useSettingsStore(
    (state) => state.processSettings.isRemoveImageInProcess,
  );

  const appConfig = useAppConfig();
  const { getDirectoryHandle } = useDirectoryHandle();
  const { generateAIImage, generateAIImageLoop } = useComfyUI();

  const getSkuIdInfoDirectoryHandle = useCallback(
    async function getSkuIdInfoDirectoryHandle(skuIdInfo: string) {
      const directoryHandle = await getDirectoryHandle();
      const skuIdInfoDirectoryHandle = await directoryHandle.getDirectoryHandle(skuIdInfo, {
        create: false,
      });
      return skuIdInfoDirectoryHandle;
    },
    [getDirectoryHandle],
  );

  // 对场景图进行处理
  // const processScenceImage = useCallback(
  //   async ({
  //     task,
  //     skuIdInfoDirectoryHandle,
  //   }: {
  //     task: TaskInfo;
  //     skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
  //   }) => {
  //     const { skuIdInfo, gigaProductId, gigaSku, available, force } = task;
  //     const scenceUrlObjects: {
  //       resultUrl?: string;
  //       resultBlob: Blob;
  //     }[] = [];

  //     const scenceImageDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
  //       appConfig.presetDirectoryNameList[0],
  //       {
  //         create: true,
  //       },
  //     );

  //     // 如果不是使用 ai 处理场景图和白底图,则直接返回原图像的文件对象
  //     if (!isUseAiProcessScenceAndWhiteImages) {
  //       const scenceFileHandles = await getAllFileHandleByDirectoryHandle(
  //         scenceImageDirectoryHandle,
  //       );
  //       await Promise.all(
  //         scenceFileHandles.map(async (fileHandle) => {
  //           const file = await fileHandle.getFile();
  //           scenceUrlObjects.push({
  //             resultBlob: file,
  //           });
  //         }),
  //       );

  //       return scenceUrlObjects;
  //     }

  //     addMessage({
  //       type: OperationMessageType.info,
  //       category: skuIdInfo,
  //       message: `场景图 ai 替换背景开始`,
  //     });
  //     const scenceCount = 4;

  //     let scenceFileHandles = await getAllFileHandleByDirectoryHandle(scenceImageDirectoryHandle);
  //     if (scenceFileHandles.length > scenceCount) {
  //       // 随机挑选 scenceCount 个成员
  //       scenceFileHandles = getRandomElements(scenceFileHandles, scenceCount);
  //     }

  //     // 对场景图进行处理
  //     await Promise.all(
  //       scenceFileHandles.map(async (fileHandle) => {
  //         const file = await fileHandle.getFile();
  //         try {
  //           const replaceBackgroundObject = await generateAIImage(file);
  //           addMessage({
  //             type: OperationMessageType.verbose,
  //             category: skuIdInfo,
  //             message: `场景图 ${file.name} 替换背景为 ${replaceBackgroundObject.resultUrl}`,
  //           });
  //           scenceUrlObjects.push(replaceBackgroundObject);
  //         } catch (error) {
  //           // 这里把替换背景的任务错误进行了拦截,这样即使出错也不会导致整个加工环境暂停。
  //           addMessage({
  //             type: OperationMessageType.error,
  //             category: skuIdInfo,
  //             message: `场景图 ${file.name} 替换背景时出现错误: ${(error as Error).message}`,
  //           });
  //         }
  //       }),
  //     );
  //     addMessage({
  //       type: OperationMessageType.success,
  //       category: skuIdInfo,
  //       message: `场景图 ai 替换背景完成`,
  //     });
  //     return scenceUrlObjects;
  //   },
  //   [generateAIImage, isUseAiProcessScenceAndWhiteImages],
  // );

  // const processWhiteBackground = useCallback(
  //   async ({
  //     task,
  //     skuIdInfoDirectoryHandle,
  //   }: {
  //     task: TaskInfo;
  //     skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
  //   }) => {
  //     const { skuIdInfo, gigaProductId, gigaSku, available, force } = task;

  //     const whiteBackgroundUrlObjects: {
  //       resultUrl?: string;
  //       resultBlob: Blob;
  //     }[] = [];
  //     const whiteBackgroundDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
  //       appConfig.presetDirectoryNameList[1],
  //       {
  //         create: true,
  //       },
  //     );

  //     // 如果不是使用 ai 处理场景图和白底图,则直接返回原图像的文件对象
  //     if (!isUseAiProcessScenceAndWhiteImages) {
  //       const whiteBackgroundFileHandles = await getAllFileHandleByDirectoryHandle(
  //         whiteBackgroundDirectoryHandle,
  //       );
  //       await Promise.all(
  //         whiteBackgroundFileHandles.map(async (fileHandle) => {
  //           const file = await fileHandle.getFile();
  //           whiteBackgroundUrlObjects.push({
  //             resultBlob: file,
  //           });
  //         }),
  //       );

  //       return whiteBackgroundUrlObjects;
  //     }

  //     const whiteBackgroundCount = 4;

  //     addMessage({
  //       type: OperationMessageType.info,
  //       category: skuIdInfo,
  //       message: `白底图 ai 替换背景开始`,
  //     });

  //     let whiteBackgroundFileHandles = await getAllFileHandleByDirectoryHandle(
  //       whiteBackgroundDirectoryHandle,
  //     );
  //     if (whiteBackgroundFileHandles.length > whiteBackgroundCount) {
  //       // 随机挑选 whiteBackgroundCount 个成员
  //       whiteBackgroundFileHandles = getRandomElements(
  //         whiteBackgroundFileHandles,
  //         whiteBackgroundCount,
  //       );
  //     }
  //     // 对白底图进行处理
  //     await Promise.all(
  //       whiteBackgroundFileHandles.map(async (fileHandle) => {
  //         const file = await fileHandle.getFile();
  //         try {
  //           const replaceBackgroundObject = await generateAIImage(file);
  //           addMessage({
  //             type: OperationMessageType.verbose,
  //             category: skuIdInfo,
  //             message: `白底图 ${file.name} 替换背景为 ${replaceBackgroundObject.resultUrl}`,
  //           });
  //           whiteBackgroundUrlObjects.push(replaceBackgroundObject);
  //         } catch (error) {
  //           // 这里把替换背景的任务错误进行了拦截,这样即使出错也不会导致整个加工环境暂停。
  //           addMessage({
  //             type: OperationMessageType.error,
  //             category: skuIdInfo,
  //             message: `白底图 ${file.name} 替换背景时出现错误: ${(error as Error).message}`,
  //           });
  //         }
  //       }),
  //     );
  //     addMessage({
  //       type: OperationMessageType.success,
  //       category: skuIdInfo,
  //       message: `白底图 ai 替换背景完成`,
  //     });
  //     return whiteBackgroundUrlObjects;
  //   },
  //   [generateAIImage, isUseAiProcessScenceAndWhiteImages],
  // );

  // // 处理尺寸图
  // const processDimensionsImage = useCallback(
  //   async ({
  //     aiGenerateUrlObject,
  //     task,
  //     skuIdInfoDirectoryHandle,
  //   }: {
  //     aiGenerateUrlObject: {
  //       resultUrl?: string;
  //       resultBlob: Blob;
  //     };
  //     task: TaskInfo;
  //     skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
  //   }) => {
  //     const { skuIdInfo, gigaProductId, gigaSku, available, force } = task;
  //     const dimensionsImageDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
  //       appConfig.presetDirectoryNameList[2],
  //       {
  //         create: true,
  //       },
  //     );
  //     const dimensionsImageFileHandles = await getAllFileHandleByDirectoryHandle(
  //       dimensionsImageDirectoryHandle,
  //     );
  //     if (dimensionsImageFileHandles.length === 0) {
  //       throw new Error('找不到尺寸图');
  //     }
  //     const dimensionsImageFileHandle = getRandomElement(dimensionsImageFileHandles);
  //     // 生成水印图
  //     const sourceBlob = await dimensionsImageFileHandle!.getFile();
  //     const watermarkImageBlob = await addImageWaterMark(
  //       sourceBlob,
  //       aiGenerateUrlObject.resultBlob,
  //     );
  //     addMessage({
  //       type: OperationMessageType.success,
  //       category: skuIdInfo,
  //       message: `尺寸图添加水印完成`,
  //     });
  //     return watermarkImageBlob;
  //   },
  //   [],
  // );

  // 处理拼接图
  // const processSpliceImage = useCallback(
  //   async ({
  //     task,
  //     skuIdInfoDirectoryHandle,
  //   }: {
  //     task: TaskInfo;
  //     skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
  //   }) => {
  //     const { skuIdInfo, gigaProductId, gigaSku, available, force } = task;
  //     const spliceImageDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
  //       appConfig.presetDirectoryNameList[3],
  //       {
  //         create: true,
  //       },
  //     );
  //     const spliceImageFileHandles = await getAllFileHandleByDirectoryHandle(
  //       spliceImageDirectoryHandle,
  //     );

  //     // 如果不要处理细节图,那么就直接返回所有的细节图像对应的文件对象
  //     if (!isUseProcessSpliceImage) {
  //       return Promise.all(spliceImageFileHandles.map((fileHandle) => fileHandle.getFile()));
  //     }

  //     if (spliceImageFileHandles.length === 0) {
  //       throw new Error('找不到细节图');
  //     }
  //     let spliceOneImageFileHandles: FileSystemFileHandle[] = [];
  //     let spliceTwoImageFileHandles: FileSystemFileHandle[] = [];
  //     const finalSpliceImageFileHandles: FileSystemFileHandle[] = spliceImageFileHandles.concat(
  //       spliceImageFileHandles,
  //       spliceImageFileHandles,
  //       spliceImageFileHandles,
  //       spliceImageFileHandles,
  //       spliceImageFileHandles,
  //       spliceImageFileHandles,
  //       spliceImageFileHandles,
  //       spliceImageFileHandles,
  //     );

  //     spliceOneImageFileHandles = finalSpliceImageFileHandles.slice(0, 4);
  //     spliceTwoImageFileHandles = finalSpliceImageFileHandles.slice(4, 8);

  //     const [spliceOneFiles, spliceTwoFiles] = await Promise.all([
  //       Promise.all(spliceOneImageFileHandles.map((fileHandle) => fileHandle.getFile())),
  //       Promise.all(spliceTwoImageFileHandles.map((fileHandle) => fileHandle.getFile())),
  //     ]);
  //     const spliceImageBlobs = await Promise.all([
  // createSpliceImage(spliceOneFiles, processSettings),
  //       createSpliceImage(spliceTwoFiles, processSettings),
  //     ]);
  //     addMessage({
  //       type: OperationMessageType.success,
  //       category: skuIdInfo,
  //       message: `生成拼接图成功`,
  //     });
  //     return spliceImageBlobs;
  //   },
  //   [processSettings, isUseProcessSpliceImage],
  // );

  const processGigaProduct = useCallback(
    async ({
      task,
      skuIdInfoDirectoryHandle,
      directoryHandle,
    }: {
      task: TaskInfo;
      skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
      directoryHandle: FileSystemDirectoryHandle;
    }) => {
      const { skuIdInfo, gigaProductId, gigaSku, available, force } = task;

      const scenceImageDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
        appConfig.presetDirectoryNameList[0],
        {
          create: true,
        },
      );
      const scenceFileHandles = await getAllFileHandleByDirectoryHandle(scenceImageDirectoryHandle);
      const scenceFiles = await Promise.all(
        scenceFileHandles.map((fileHandle) => fileHandle.getFile()),
      );
      const copyScenceFiles = [...scenceFiles];
      const scenceLength = scenceFiles.length;

      const whiteBackgroundDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
        appConfig.presetDirectoryNameList[1],
        {
          create: true,
        },
      );
      const whiteBackgroundFileHandles = await getAllFileHandleByDirectoryHandle(
        whiteBackgroundDirectoryHandle,
      );
      const whiteBackgroundFiles = await Promise.all(
        whiteBackgroundFileHandles.map((fileHandle) => fileHandle.getFile()),
      );
      const copyWhiteBackgroundFiles = [...whiteBackgroundFiles];
      const whiteBackgroundLength = whiteBackgroundFiles.length;

      const dimensionsImageDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
        appConfig.presetDirectoryNameList[2],
        {
          create: true,
        },
      );
      const dimensionsImageFileHandles = await getAllFileHandleByDirectoryHandle(
        dimensionsImageDirectoryHandle,
      );
      const dimensionsImageFiles = await Promise.all(
        dimensionsImageFileHandles.map((fileHandle) => fileHandle.getFile()),
      );
      const copyDimensionsImageFiles = [...dimensionsImageFiles];
      const dimensionsLength = dimensionsImageFiles.length;

      const spliceImageDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
        appConfig.presetDirectoryNameList[3],
        {
          create: true,
        },
      );
      const spliceImageFileHandles = await getAllFileHandleByDirectoryHandle(
        spliceImageDirectoryHandle,
      );
      const spliceImageFiles = await Promise.all(
        spliceImageFileHandles.map((fileHandle) => fileHandle.getFile()),
      );
      const copySpliceImageFiles = [...spliceImageFiles];
      const spliceLength = spliceImageFiles.length;

      // 白底图和场景图的组合
      const copyScenceAndWhiteBackgroundFiles = [...copyScenceFiles, ...copyWhiteBackgroundFiles];

      if (scenceLength + whiteBackgroundLength < 2) {
        throw new Error('场景图和白底图至少需要两张');
      }

      let imageBlobs: Blob[] = [];
      // 先处理前八张
      // 如果不用 ai 加工
      // 生成前两张图
      if (scenceLength >= 2) {
        imageBlobs.push(scenceFiles.shift()!);
        imageBlobs.push(scenceFiles.shift()!);
      } else if (scenceLength === 1) {
        imageBlobs.push(scenceFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
      } else {
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
      }

      // 开始生产水印图
      if (dimensionsLength > 0) {
        const dimensionsFile = dimensionsImageFiles[0];
        const watermarkImageBlob = await addImageWaterMark(
          dimensionsFile,
          // 从前两张图中挑选一张作为水印
          getRandomElement(imageBlobs)!,
        );
        imageBlobs.push(watermarkImageBlob);
      } else {
        const watermarkImageBlob = await addImageWaterMark(imageBlobs[1], imageBlobs[0]);
        imageBlobs.push(watermarkImageBlob);
      }
      addMessage({
        type: OperationMessageType.success,
        category: skuIdInfo,
        message: `添加水印完成`,
      });

      // 生成后 5 张图
      if (scenceFiles.length >= 2 && whiteBackgroundFiles.length >= 3) {
        imageBlobs.push(scenceFiles.shift()!);
        imageBlobs.push(scenceFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
      } else if (scenceFiles.length === 1 && whiteBackgroundFiles.length >= 4) {
        imageBlobs.push(scenceFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
      } else if (scenceFiles.length === 0 && whiteBackgroundFiles.length >= 5) {
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
        imageBlobs.push(whiteBackgroundFiles.shift()!);
      } else {
        // 凑够 5 张
        const restLength = scenceFiles.length + whiteBackgroundFiles.length;
        const scenceAndWhiteBackgroundFiles = [...scenceFiles, ...whiteBackgroundFiles];
        if (restLength >= 5) {
          imageBlobs.push(scenceAndWhiteBackgroundFiles.pop()!);
          imageBlobs.push(scenceAndWhiteBackgroundFiles.shift()!);
          imageBlobs.push(scenceAndWhiteBackgroundFiles.pop()!);
          imageBlobs.push(scenceAndWhiteBackgroundFiles.shift()!);
          imageBlobs.push(scenceAndWhiteBackgroundFiles.pop()!);
        } else {
          const lackLength = 5 - restLength;
          for (let i = 0; i < restLength; i++) {
            if (i % 2 === 0) {
              imageBlobs.push(scenceAndWhiteBackgroundFiles.pop()!);
            } else {
              imageBlobs.push(scenceAndWhiteBackgroundFiles.shift()!);
            }
          }
          for (let i = 0; i < lackLength; i++) {
            imageBlobs.push(getRandomElement(copyScenceAndWhiteBackgroundFiles)!);
          }
        }
      }

      // 生成拼接图
      if (isUseProcessSpliceImage) {
        // 第九张使用随机的白底图/场景图
        imageBlobs.push(getRandomElement(copyScenceAndWhiteBackgroundFiles)!);
        let files: File[] = [];
        if (spliceImageFiles.length >= 4) {
          files = spliceImageFiles.slice(0, 4);
        } else if (spliceImageFiles.length === 3) {
          if (dimensionsImageFiles.length >= 1) {
            files = [dimensionsImageFiles[0], ...spliceImageFiles.slice(0, 3)];
          } else {
            files = [
              getRandomElement(copyScenceAndWhiteBackgroundFiles)!,
              ...spliceImageFiles.slice(0, 3),
            ];
          }
        } else if (spliceImageFiles.length === 2) {
          if (dimensionsImageFiles.length >= 1) {
            files = [
              dimensionsImageFiles[0],
              ...spliceImageFiles.slice(0, 2),
              getRandomElement(copyScenceAndWhiteBackgroundFiles)!,
            ];
          } else {
            files = [
              ...spliceImageFiles.slice(0, 2),
              copyScenceAndWhiteBackgroundFiles.pop()!,
              copyScenceAndWhiteBackgroundFiles.shift()!,
            ];
          }
        } else if (spliceImageFiles.length === 1) {
          if (dimensionsImageFiles.length >= 1) {
            files = [
              dimensionsImageFiles[0],
              ...spliceImageFiles.slice(0, 1),
              copyScenceAndWhiteBackgroundFiles.pop()!,
              copyScenceAndWhiteBackgroundFiles.shift()!,
            ];
          } else {
            files = [
              ...spliceImageFiles.slice(0, 1),
              copyScenceAndWhiteBackgroundFiles.pop()!,
              copyScenceAndWhiteBackgroundFiles.shift()!,
              copyScenceAndWhiteBackgroundFiles.pop()!,
            ];
          }
        } else {
          files = [
            copyScenceAndWhiteBackgroundFiles.pop()!,
            copyScenceAndWhiteBackgroundFiles.shift()!,
            copyScenceAndWhiteBackgroundFiles.pop()!,
            copyScenceAndWhiteBackgroundFiles.shift()!,
          ];
        }
        const spliceImageBlob = await createSpliceImage(files, processSettings);
        imageBlobs.push(spliceImageBlob);
      } else {
        // 不生成拼接图
        if (spliceLength >= 2) {
          imageBlobs.push(spliceImageFiles.shift()!);
          imageBlobs.push(spliceImageFiles.shift()!);
        } else if (spliceLength === 1) {
          if (dimensionsImageFiles.length >= 1) {
            imageBlobs.push(dimensionsImageFiles.pop()!);
            imageBlobs.push(spliceImageFiles.shift()!);
          } else {
            imageBlobs.push(getRandomElement(copyScenceAndWhiteBackgroundFiles)!);
            imageBlobs.push(spliceImageFiles.shift()!);
          }
        } else {
          if (dimensionsImageFiles.length >= 1) {
            imageBlobs.push(dimensionsImageFiles.pop()!);
            imageBlobs.push(getRandomElement(copyScenceAndWhiteBackgroundFiles)!);
          } else {
            imageBlobs.push(getRandomElement(copyScenceAndWhiteBackgroundFiles)!);
            imageBlobs.push(getRandomElement(copyScenceAndWhiteBackgroundFiles)!);
          }
        }
      }

      if (isUseAiProcessScenceAndWhiteImages) {
        // 对 imageBlobs 中的 1, 2, 4, 5, 6, 7, 8 进行 ai 加工
        const needAiBlobs = imageBlobs.filter((_, index) =>
          [1, 2, 4, 5, 6, 7, 8].includes(index + 1),
        );
        if (isUseProcessSpliceImage) {
          // 那么第九张都要处理
          needAiBlobs.push(imageBlobs[8]);
        }
        addMessage({
          type: OperationMessageType.info,
          category: skuIdInfo,
          message: `ai 替换背景开始`,
        });
        let aiImageBlobs = await Promise.all(
          needAiBlobs.map(async (blob) => {
            try {
              const replaceBackgroundObject = await generateAIImageLoop(
                blob,
                processSettings.aiRetryTime,
                (error) => {
                  addMessage({
                    type: OperationMessageType.error,
                    category: skuIdInfo,
                    // @ts-ignore
                    message: `处理 ${blob.name}  替换背景时出错 ${(error as Error).message},正在进行重试`,
                  });
                },
              );
              addMessage({
                type: OperationMessageType.verbose,
                category: skuIdInfo,
                // @ts-ignore
                message: `处理 ${blob.name}  替换背景为 ${replaceBackgroundObject.resultUrl}`,
              });
              return replaceBackgroundObject.resultBlob;
            } catch (error) {
              // 这里把替换背景的任务错误进行了拦截,当 ai 加工错误时直接报错,而不执行后续流程
              addMessage({
                type: OperationMessageType.error,
                category: skuIdInfo,
                // @ts-ignore
                message: `处理 ${blob.name} 替换背景时出现错误: ${(error as Error).message}`,
              });
              // @ts-ignore
              throw new Error(`处理 ${blob.name} 替换背景时出现错误: ${(error as Error).message}`);
            }
          }),
        );
        aiImageBlobs.splice(2, 0, imageBlobs[2]);
        if (isUseProcessSpliceImage) {
          imageBlobs = [...aiImageBlobs, imageBlobs[9]];
        } else {
          imageBlobs = [...aiImageBlobs, imageBlobs[8], imageBlobs[9]];
        }
      }

      // 对生成的场景图和白底图生成滤镜
      if (isFilterProcessScenceAndWhiteImages) {
        imageBlobs = await Promise.all(
          imageBlobs.map(async (imageBlob, index) => {
            // 如果是第三张图已经处理过了,那么就不进行处理
            if (index === 2 || index === 9) {
              return imageBlob;
            }
            // 如果是使用拼接,那么第九张都要处理,否则只处理 1 到 8 张
            if (!isUseProcessSpliceImage && index === 8) {
              return imageBlob;
            }
            // 从场景图中随机挑选一张
            let filterImageBlob = getRandomElement(copyScenceFiles)!;
            if (copyScenceFiles.length === 0) {
              filterImageBlob = getRandomElement(copyScenceAndWhiteBackgroundFiles)!;
            }
            const watermarkImageBlob = await addImageWaterMark(imageBlob, filterImageBlob);
            // console.log(filterImageBlob, watermarkImageBlob, imageBlobs);
            return watermarkImageBlob;
          }),
        );
      }

      const imagesDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
        appConfig.imagesDirectoryname,
        {
          create: true,
        },
      );

      // 在写入前决定是否删除图片
      if (isRemoveImageInProcess) {
        await removeAllFilesInDirectory(imagesDirectoryHandle);
      }

      // 写入到录播图
      await Promise.all(
        imageBlobs.map(async (blob, index) => {
          const fileHandle = await imagesDirectoryHandle.getFileHandle(
            `${index + 1}${mimeToExtMap[blob.type] || '.jpg'}`,
            {
              create: true,
            },
          );
          const writable = await fileHandle.createWritable();
          await writable.write(blob);
          await writable.close();
        }),
      );

      addMessage({
        category: skuIdInfo,
        type: OperationMessageType.success,
        message: `成功把生成的图片保存到${appConfig.imagesDirectoryname}目录下`,
      });
    },
    [
      // processScenceImage,
      // processWhiteBackground,
      // processDimensionsImage,
      // processSpliceImage,
      isUseAiProcessScenceAndWhiteImages,
      isUseProcessSpliceImage,
      isRemoveImageInProcess,
      isFilterProcessScenceAndWhiteImages,
      processSettings,
    ],
  );

  const processProduct = useCallback(
    async function processProduct(task: TaskInfo) {
      const { skuIdInfo, gigaProductId, gigaSku, available, force } = task;

      if (processingProduct[skuIdInfo]) {
        toast.info(`货号 ${skuIdInfo} 正在加工中`);
        return;
      }

      processingProduct[skuIdInfo] = true;

      const directoryHandle = await getDirectoryHandle();

      // 获取货号目录
      const skuIdInfoDirectoryHandle = await getSkuIdInfoDirectoryHandle(skuIdInfo).catch(
        (error) => {
          processingProduct[skuIdInfo] = false;
          throw error;
        },
      );
      try {
        resetAndAddMessage({
          type: OperationMessageType.info,
          category: skuIdInfo,
          message: '开始加工产品',
        });
        toast.info(`${skuIdInfo}: 加工开始`);

        if (!force) {
          const state = await getProductState(
            appConfig.productStateFilename,
            skuIdInfoDirectoryHandle,
          );
          if (state.processState === ProcessState.success) {
            addMessage({
              category: skuIdInfo,
              type: OperationMessageType.success,
              message: `该产品已经加工过了 ${doneMessage}`,
            });
            toast.success(`${skuIdInfo}: 已经加工过了`);
            processingProduct[skuIdInfo] = false;
            return;
          }
        }

        // 开始进行加工
        await processGigaProduct({
          task,
          skuIdInfoDirectoryHandle,
          directoryHandle,
        });

        // 创建加工完成的状态
        await setProductState(
          {
            [StateType.process]: ProcessState.success,
          },
          appConfig.productStateFilename,
          skuIdInfoDirectoryHandle,
        );
        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.success,
          message: `加工产品成功 ${doneMessage}`,
        });
        toast.success(`${skuIdInfo}: 加工成功`);

        processingProduct[skuIdInfo] = false;
      } catch (error) {
        // 创建采集失败的状态
        await setProductState(
          {
            [StateType.process]: ProcessState.error,
          },
          appConfig.productStateFilename,
          skuIdInfoDirectoryHandle,
        );

        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.error,
          message: `加工产品失败: ${(error as Error).message}`,
        });
        processingProduct[skuIdInfo] = false;
      }
    },
    [getSkuIdInfoDirectoryHandle, processGigaProduct],
  );

  return {
    processProduct,
  };
}
